/*
 * Daniel R Padilla
 *
 * Copyright (c) 2007, Daniel R Padilla
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package org.databasefacade.table.column;


import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;


public class RoundValue {
    public static BigDecimal moneyType(BigDecimal money) {
        try {
            String num = money.toPlainString();

            if (num.contains(".")) {
                int prec = getLeftOfDecimalIntValue(num);

                if (prec > 0) {
                    MathContext mc = new MathContext(2, RoundingMode.UP);

                    money = money.round(mc);
                }
            }
        } catch (Exception e) {
            return money;
        }
        return money;
    }

    public static BigDecimal floatType(BigDecimal num) {

        try {
            String numstr = num.toPlainString();

            if (numstr.contains(".")) {
                int prec = getLeftOfDecimalIntValue(numstr);

                if (prec > 0) {
                    MathContext mc = new MathContext(6, RoundingMode.UP);

                    num = num.round(mc);
                }
            }
        } catch (Exception e) {
            return num;
        }
        return num;
    }
    
    private static int getLeftOfDecimalIntValue(String numstr) {
        numstr = numstr.substring(numstr.indexOf(".") + 1);
        if (numstr.contains("e")) {
            numstr.substring(0, numstr.indexOf("e"));
        }
        if (numstr.contains("E")) {
            numstr.substring(0, numstr.indexOf("E"));
        }
        return Integer.valueOf(numstr);
    }
}
